import { DirectiveBinding } from 'vue'

interface HTMLDOM extends HTMLElement {
  __selectAll__?: Function
}

interface INPUTF extends HTMLInputElement {
  __selectAll__?: Function
}

export default {
  mounted(el: HTMLDOM, binding: DirectiveBinding<boolean>, vnode: any) {
    // 添加事件监听
    const input = el.querySelector('input')
    if (binding.value) {
      try {
        input?.focus()
        input?.select()
      } catch {
        console.warn(`el.querySelector('input')`, input)
      }
    }

    function selectAll() {
      input?.select()
    }
    el.__selectAll__ = selectAll

    input?.addEventListener('focus', selectAll)
  },
  updated(el: HTMLBodyElement, binding: DirectiveBinding<boolean>, vnode: any) {
    const input = el.querySelector('input')
    if (binding.value) {
      try {
        input?.focus()
      } catch {
        console.warn(`updated el.querySelector('input')`, input)
      }
    }
  },
  beforeUnmount(el: HTMLDOM) {
    const input = el.querySelector('input') as INPUTF
    // 移除事件监听
    input?.removeEventListener('focus', el.__selectAll__)
    // 删除无用属性
    delete el.__selectAll__
  },
}
